# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.channel.pay import check_channel_order
from common.order.db import get_pay, add_pay_success
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import SignError, NotPayOrderError, ProcessedPayOrderError, NotResponsePayIdError
from common.utils.ip_address import check_valid_ip_address

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '1774': {
        'API_KEY': '11dde30037f442e187892f29c80fe007',
    },
    'gateway': 'http://pay.zhongfapay.com/bank/',
}


def _get_pay_type(service):
    if service == 'alipay':  # 支付宝
        return '992'
    if service == 'alipay_wap':  # 支付宝wap
        return '1006'
    elif service == 'wechat':  # 微信
        return '1004'
    elif service == 'union':  # 云闪付
        return '1012'
    else:
        return '992'


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway():
    return APP_CONF['gateway']


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf-8'))
    return m.hexdigest()


#  创建订单sign
def generate_verify_sign(parameter, key):
    s = 'parter=%s&type=%s&value=%s&orderid=%s&callbackurl=%s%s' \
        % (parameter['parter'], parameter['type'], parameter['value'],
           parameter['orderid'], parameter['callbackurl'], key)
    return _gen_sign(s)


# 异步回调签名验证
def verify_notify_sign(parameter, key):
    s = 'orderid=%s&opstate=%s&ovalue=%s%s' % (parameter['orderid'], parameter['opstate'],
                                               parameter['ovalue'], key)
    sign = parameter['sign']
    calculated_sign = _gen_sign(s)
    if sign != calculated_sign:
        _LOGGER.info("zhongfapay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise SignError('sign not pass, data: %s' % parameter)


def _build_form(params, gateway):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + gateway + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>doc" \
            "ument.forms['submit'].submit();</script>"
    return html


def create_charge(pay, pay_amount, info):
    app_id = info['app_id']
    service = info.get('service')
    api_key = _get_api_key(app_id)

    parameter_dict = OrderedDict((
        ('parter', app_id),  # 商户ID
        ('type', _get_pay_type(service)),  # 银行类型
        ('value', '%.2f' % float(pay_amount)),  # 支付金额 元
        ('orderid', str(pay.id)),  # 商户订单号
        ('callbackurl', '{}/pay/api/{}/zhongfapay/{}'.format(
            settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('hrefbackurl', '{}/pay/api/{}/zhongfapay/'.format(
            settings.NOTIFY_PREFIX, settings.RETURN_PATH)),
        ('payerIp', _get_device_ip(info)),  # 支付用户 IP
        ('attach', 'none'),  # 备注
        ('kjuser', str(pay.id)),  # 付款人 ID
    ))
    parameter_dict['sign'] = generate_verify_sign(parameter_dict, api_key)

    json_parameter = json.dumps(parameter_dict)
    _LOGGER.info("zhongfapay create date: %s, order_id is: %s", json_parameter,
                 parameter_dict['orderid'])

    html_text = _build_form(parameter_dict, _get_gateway())
    cache_id = redis_cache.save_html(pay.id, html_text)
    url = settings.PAY_CACHE_URL + cache_id
    _LOGGER.info('zhongfapay pay url: %s', url)
    return {'charge_info': url}


# success异步回调
def check_notify_sign(request, app_id):
    _LOGGER.info("zhongfapay notify body: %s", request.body)
    data = dict(request.GET.items())
    _LOGGER.info("zhongfapay notify data: %s, order_id is: %s", data, data['orderid'])
    verify_notify_sign(data, _get_api_key(app_id))
    pay_id = data['orderid']
    check_valid_ip_address(str(request.META['REMOTE_ADDR']), pay_id)
    if not pay_id:
        _LOGGER.error("zhongfapay notify fatal error, pay object not exists, data: %s" % data)
        raise NotResponsePayIdError('event does not contain valid pay ID')
    pay = get_pay(pay_id)
    if not pay:
        raise NotPayOrderError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        if pay.status == PAY_STATUS.SUCC:
            _LOGGER.info('zhongfapay %s has been processed and pay succeeded' % pay_id)
            return
        raise ProcessedPayOrderError('pay %s has been processed and not pay success' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['opstate'])
    trade_no = data['orderid']
    total_fee = float(data['ovalue'])
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee,
    }
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == '0':
        _LOGGER.info('zhongfapay check order success, user_id:%s pay_id:%s' % (mch_id, pay_id))
        add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


# 暂无查询接口
def query_charge(pay_order, app_id):
    pass
